﻿using MESPro.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using MESPro.Global;
using MESPro.DBManager;
using System.Diagnostics;
using MESPro.Enums;

namespace MESPro.Views
{
    public class Rolecom : IEqualityComparer<Role>
    {
        #region Public 方法

        public bool Equals(Role x, Role y)
        {
            return x.Id == y.Id;
        }

        public int GetHashCode(Role obj)
        {
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return obj.ToString().GetHashCode();
            }
        }

        #endregion Public 方法
    }
    public partial class MainClientFrm : Form
    {

        #region Public Constructors

        public MainClientFrm()
        {
            InitializeComponent();
            CommonEX.InitLanguage(this.语言ToolStripMenuItem, 刷新界面);
            RMShowMsg += this.ShowMsg;
            imageList1.Init();
            this.treeView1.ImageList = imageList1;
            this.Load += MainClientFrm_Load;
        }
        public MainClientFrm(User? user, Model model) : this()
        {
            this.LoginModel = model;
        }

        #endregion Public Constructors

        #region 字段

        public static Action<object, MsgLevel>? RMShowMsg;

        public Model? Model;

        public Model? LoginModel;

        /// <summary>
        /// 增加编辑的窗体
        /// </summary>
        Dictionary<Function, RuningFrm> DesignerList
            = new Dictionary<Function, RuningFrm>();

        #endregion 字段

        #region Internal 方法

        internal void ShowMsg(object msg, MsgLevel level)
        {
            ListViewItem item = new ListViewItem();
            item.ForeColor = Color.Red;
            item.ImageKey = $"{level.ToString()}.ico";
            item.Text = DateTime.Now.ToString();
            item.SubItems.Add(msg.ToString());
            this.listView1.Items.Insert(0, item);
        }

        #endregion Internal 方法

        #region Private 方法

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private async Task 刷新界面()
        {
            DesignerList.ToList().ForEach(x => { x.Value.Close(); x.Value.Dispose(); });
            DesignerList.Clear();
            if (LoginModel == null) return;
            Model = await Task.Run(() =>
            {
                return DbContext.Db
                       .Queryable<Model>()
                       .Where(x => x.Id == LoginModel.Id)
                       .Includes(
                       a => a.FunctionGroups,
                       b => b.Functions.Where(x => x.Roles.Any(y => y.Id == 1)).ToList(),
                       c => c.DbControlGs)
                           .ToList()[0];
            });
            CommonEX.InitTreeView(this.treeView1, Model.FunctionGroups);

        }
        private async void MainClientFrm_Load(object sender, EventArgs e)
        {
            if (LoginModel == null) return;
            var rid = App.User.Roles.Select(x => x.Id).ToList();
            var r = DbContext.Db.Queryable<Role>().ToList();
            Model = await Task.Run(() =>
            {
                var models = DbContext.Db
                       .Queryable<Model>()
                       .Where(x => x.Id == LoginModel.Id)
                       .Includes(
                       a => a.FunctionGroups,
                       b => b.Functions,
                       c => c.DbControlGs)
                       .ToList();
                models.ForEach(x => x.FunctionGroups
                           .ForEach(x => x.Functions.ForEach((x) =>
                           {
                               if (x.Roles == null)//cancel
                               {
                                   //var f = DbContext.Db.Queryable<Function>()
                                   //.Includes(x => x.Roles)
                                   //.ToList();
                                   //x.Roles = f.FirstOrDefault(xx => xx.Id == x.Id).Roles;
                                   x.Roles = DbContext.Db
                                                    .Queryable<Function>()
                                                    .Includes(x => x.Roles)
                                                    .First(xx => xx.Id == x.Id).Roles;
                                   //x.Roles = f.Roles;
                               }
                           })));
                foreach (var item in models)
                {
                    foreach (var fg in item.FunctionGroups)
                    {
                        fg.Functions = fg.Functions.Where(y => y.Roles.Any(z => rid.Contains(z.Id))).ToList();
                    }
                }

                if (models.Count > 0)
                {
                    return models[0];
                }
                else
                {
                    return null;
                }
            });

            //Model = DbContext.Db
            //    .Queryable<Model>()
            //    .Where(x => x.DisName == LoginModel.DisName)
            //    .Includes(
            //    a => a.FunctionGroups,
            //    b => b.Functions,
            //    c => c.DbControlGs)
            //    .ToList()[0];
            CommonEX.InitTreeView(this.treeView1, Model.FunctionGroups);
        }
        private void 展开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.splitContainer1.SplitterDistance = 120;
        }

        private void 收缩ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ss = this.splitContainer1.SplitterDistance;
            this.splitContainer1.SplitterDistance = 0;
            var ss2 = this.splitContainer1.SplitterDistance;
        }
        private async void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {

            if (e.Node.Level == 1)
            {
                var obj = e.Node;
                // this.propertyFrm.propertyGrid1.SelectedObject = obj.Tag;
                if (obj.Tag is Function func)
                {
                    if (DesignerList.TryGetValue(func, out RuningFrm aa))
                    {

                        aa.Show(dockPanel1, DockState.Document);
                    }
                    else
                    {
                        RuningFrm designer = new RuningFrm();

                        designer.FormClosed += (sender, e) =>
                        {
                            DesignerList.Remove((sender as RuningFrm).Function);
                        };
                        designer.Show(dockPanel1, DockState.Document);
                        designer.Function = func;
                        //await Task.Delay(100);
                        designer.BuildView();
                        await designer.QueryAll();
                        designer.TabText = func.DisName;
                        designer.Text = func.DisName;
                        DesignerList.Add(func, designer);
                    }

                }
            }
        }

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.listView1.Clear();
        }

        #endregion Private 方法

    }
}
